import { ref,computed } from 'vue'

export const useHistory = () => {
  const history = ref([])
  const currentIndex = ref(-1)

  const recordState = (state) => {
    history.value = history.value.slice(0, currentIndex.value + 1)
    history.value.push(state)
    currentIndex.value++
  }

  const undo = () => {
    if (currentIndex.value > 0) {
      currentIndex.value--
      return history.value[currentIndex.value]
    }
    return history.value[0]
  }

  const redo = () => {
    if (currentIndex.value < history.value.length - 1) {
      currentIndex.value++
      return history.value[currentIndex.value]
    }
    return history.value[currentIndex.value]
  }

  return {
    undo,
    redo,
    recordState,
    canUndo: computed(() => currentIndex.value > 0),
    canRedo: computed(() => currentIndex.value < history.value.length - 1)
  }
}